package sf.dsl.example;

import sf.database.dialect.DBDialect;
import sf.database.jdbc.sql.SQLParameter;
import sf.tools.ArrayUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 数据库 聚合函数，例如 count(id) ，max(account.age) 等等
 */
public class FunctionSimpleField extends SimpleField {

    /**
     * 左边字符串 如: max(
     */
    protected String left = "";
    /**
     * 右边字符串 如:)
     */
    protected String right = "";
    /**
     *
     */
    protected SimpleField[] fields;

    public FunctionSimpleField() {
    }

    /**
     * @param fnName 方法名称,如:max
     * @param column
     */
    public FunctionSimpleField(String fnName, String... column) {
        this.left = fnName + "(";
        this.right = ")";
        if (ArrayUtils.isNotEmpty(column)) {
            fields = DSLMethod.toArray(column);
        }
    }

    /**
     * @param fnName  方法名称,如:max
     * @param columns
     */
    public FunctionSimpleField(String fnName, SimpleField... columns) {
        this.left = fnName + "(";
        this.right = ")";
        this.fields = columns;
    }

    public FunctionSimpleField left(String left) {
        this.left = left;
        return this;
    }

    public FunctionSimpleField right(String right) {
        this.right = right;
        return this;
    }

    public FunctionSimpleField fileds(String... column) {
        this.fields = DSLMethod.toArray(column);
        return this;
    }

    public FunctionSimpleField fileds(SimpleField... fields) {
        this.fields = fields;
        return this;
    }

    public SimpleField[] getFields() {
        return fields;
    }

    public void setFields(SimpleField[] fields) {
        this.fields = fields;
    }

    @Override
    public void toConditionSql(StringBuilder sb, List<SQLParameter> list, AtomicBoolean useDefaultTableNameAlias, boolean useTablePrefix, DBDialect dialect) {
        if (ArrayUtils.isNotEmpty(fields)) {
            sb.append(left);
            boolean flag = false;
            for (SimpleField column : fields) {
                if (flag) {
                    sb.append(',');
                }
                flag = true;
                column.toConditionSql(sb, list, useDefaultTableNameAlias, useTablePrefix, dialect);
            }
            sb.append(right);
        }
    }
}
